home *** CD-ROM | disk | FTP | other *** search
/ Aminet 7 / Aminet 7 - August 1995.iso / Aminet / docs / misc / ConcNews.lha / news / general.programming / comp.sys.amiga.programmer_2566_000007.msg < prev    next >
Encoding:
Text File  |  1994-11-27  |  1.4 KB  |  41 lines

  1. Newsgroups: comp.sys.amiga.programmer
  2. Path: dd.chalmers.se!news.chalmers.se!sunic!pipex!howland.reston.ans.net!sol.ctr.columbia.edu!news.kei.com!yeshua.marcam.com!zip.eecs.umich.edu!umn.edu!kksys.com!haapi!bee!sar
  3. From: sar@bee.beehive.mn.org (Steven A. Reisman)
  4. Subject: Re: counting 1 bits
  5. References: <1993Dec13.142639.12004@cs.kuleuven.ac.be>
  6. Organization: Steven Reisman & Associates
  7. Date: Tue, 14 Dec 1993 04:29:00 GMT
  8. X-Newsreader: TIN [version 1.1 PL8]
  9. Message-ID: <1993Dec14.042900.10161@bee.beehive.mn.org>
  10. Lines: 29
  11.  
  12. Stefaan Decorte (stefaan@cs.kuleuven.ac.be) wrote:
  13.  
  14. : Does there exist an (efficient) instruction to count the number of 1 bits in a 
  15. : unsigned long data type?  (preferably in C but assembler is also ok).
  16. : Or does there exist a way around performing the inefficient 32-part loop?
  17.  
  18. Try the following:
  19.  
  20.  
  21. #include <stdio.h>
  22.  
  23. int    cardcount(unsigned long x)
  24. {
  25.     x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
  26.     x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  27.     x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
  28.     return x % 255;
  29. }
  30.  
  31. main ()
  32. {
  33.   printf("%d\n", cardcount(0xFFFFFFFF));
  34.   printf("%d\n", cardcount(0x12345678));
  35.   printf("%d\n", cardcount(0x12481248));
  36. }
  37. -- 
  38. Steven A. Reisman
  39. 12695 4th St. S.                                  sar@beehive.mn.org      
  40. Afton, MN  55001                                      (612) 436-7125
  41.